

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import com.clsfd.database.DatabaseConnection;
import com.clsfd.database.SystemParams;
import com.clsfd.sms.SMSHandler;
import com.clsfd.ussd.UssdMenu;
import com.clsfd.ussd.UssdMenuItem;
import com.logging.DcLogFormatter;


/**
 * Servlet implementation class ussdreceiver
 */
@WebServlet("/ussdreceiver")
public class ussdreceiver extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private Logger Log=null;
    private DatabaseConnection Databaseconn= null;
	private SMSHandler SmsHandler = null;
    private SystemParams SysParams=null;
    private int VehiclesParentid=0;
    private int LandsParentid=0;
    public ussdreceiver() {
        super();
        try{
        	
        	Databaseconn = new DatabaseConnection(null);
        	SysParams = Databaseconn.getSystemParameters();
        	SmsHandler = new SMSHandler(SysParams);    		
	        FileHandler filehandler = new FileHandler(SysParams.getSmsHandlerLogFile()+"%g.log",1000000000,3,true);
			Formatter formatterTxt=new DcLogFormatter();
			filehandler.setFormatter(formatterTxt);
			Log = Logger.getLogger("USSDHandler");
			Log.addHandler(filehandler);
			Log.setLevel(Level.parse(SysParams.getSmsHandlerLogLevel()));
			VehiclesParentid=Integer.parseInt(SysParams.getParameter("Vehicles Parent ID"));
			LandsParentid=Integer.parseInt(SysParams.getParameter("Lands Parent ID"));
        }catch(Exception e){
        	e.printStackTrace();
        }
    }

    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String MenuID=request.getParameter("menuid");	
			HttpSession session = request.getSession(true);		
			String Msisdn = (String) session.getAttribute("msisdn");
			if(Msisdn==null){
				Msisdn=request.getParameter("msisdn");
				session.setAttribute("msisdn", Msisdn);
			}
			
			
			UssdMenu ussdMenu = new UssdMenu();
			
			if (MenuID==null || Msisdn==null)
			{
				ussdMenu.setAction("Notification");
				ussdMenu.setHeading("null Point man");
				
			}
			else if (MenuID.equalsIgnoreCase("MainMenu"))
			{
				ussdMenu.setAction("ShowMenu");
				ussdMenu.setHeading("Welcome to DC CLSFD");
				ussdMenu.setMenuItem(new UssdMenuItem [] {
						new UssdMenuItem("Enter the Vehicles Section", "http://localhost:8080/smsreceiver/ussdreceiver?msisdn=%MSISDN%&menuid=vehiclemain"), 
						new UssdMenuItem("Enter the Lands Section", "http://localhost:8080/smsreceiver/ussdreceiver?msisdn=%MSISDN%&menuid=landsmain"),
						new UssdMenuItem("Manage Your Profile", "http://localhost:8080/smsreceiver/ussdreceiver?msisdn=%MSISDN%&menuid=ManageProfile")
				});
			}
			else if (MenuID.equalsIgnoreCase("vehiclemain"))
			{
				ussdMenu.setAction("ShowMenu");
				ussdMenu.setNomatch("Invalid Input.\nWhat's Your Plan ?");
				ussdMenu.setHeading("What's Your Plan ?");
				ussdMenu.setHasBack(true);
				ussdMenu.setMenuItem(new UssdMenuItem [] {
						new UssdMenuItem("Buy my Dream Vehicle", "http://localhost:8080/smsreceiver/ussdreceiver?msisdn=%MSISDN%&menuid=buyvehiclemain"),
						new UssdMenuItem("Sell out my Vehicle", "http://localhost:8080/smsreceiver/ussdreceiver?msisdn=%MSISDN%&menuid=sellvehiclemain")					
				});
			}
			else if (MenuID.equalsIgnoreCase("buyvehiclemain"))
			{
				ussdMenu.setAction("ShowMenu");
				ussdMenu.setHasBack(true);
				ussdMenu.setHasHome(true);	
				ussdMenu.setHeading("Get to know about the Sellers");
				ussdMenu.setMenuItem(new UssdMenuItem [] {
						new UssdMenuItem("Enter the Vehicle Details", "http://localhost:8080/smsreceiver/ussdreceiver?msisdn=%MSISDN%&servicetype=vehicles&menuid=buyergetinfo&currentlevel=0"), 
						new UssdMenuItem("Manage your previous Subscriptions", "http://localhost:8080/smsreceiver/ussdreceiver?msisdn=%MSISDN%&menuid=managevehiclesubscriptions")					
				});
			}
			else if (MenuID.equalsIgnoreCase("buyergetinfo"))
			{
				String servicetype=request.getParameter("servicetype");				
				int Currentlevel=Integer.parseInt(request.getParameter("currentlevel"));
				int parentid=0;
				if (Currentlevel==0){
					parentid=servicetype.equals("vehicles")?VehiclesParentid:LandsParentid;
				}
				else if (Currentlevel==1){
					parentid=Integer.parseInt(request.getParameter("selectionid"));
					session.setAttribute("Level1", parentid);
					session.setAttribute("Level1Text", request.getParameter("selectiontext"));
				}
				else if (Currentlevel==2){
					parentid=Integer.parseInt(request.getParameter("selectionid"));
					session.setAttribute("Level2", parentid);
					session.setAttribute("Level2Text", request.getParameter("selectiontext"));
				}
				else if (Currentlevel==3){
					parentid=Integer.parseInt(request.getParameter("selectionid"));
					session.setAttribute("Level3", parentid);
					session.setAttribute("Level3Text", request.getParameter("selectiontext"));
				}
				else if (Currentlevel==4){
					parentid=Integer.parseInt(request.getParameter("selectionid"));
					session.setAttribute("Level4", parentid);
					session.setAttribute("Level4Text", request.getParameter("selectiontext"));
				}
				else if (Currentlevel==5){
					parentid=Integer.parseInt(request.getParameter("selectionid"));
					session.setAttribute("Level5", parentid);
					session.setAttribute("Level5Text", request.getParameter("selectiontext"));
				}
				HashMap<Integer, String> items=Databaseconn.getClassifiedItemByParent(parentid);
				if (items.size()>0)
				{
					Set<Entry<Integer,String>> itemset=	items.entrySet();
					UssdMenuItem [] menuitems= new UssdMenuItem[items.size()];
					int i=0;
					for (Entry<Integer, String> entry : itemset) {
						menuitems[i]= new UssdMenuItem(entry.getValue(), "http://localhost:8080/smsreceiver/ussdreceiver?msisdn=%MSISDN%&servicetype=vehicle&menuid=buyergetinfo&currentlevel="+(Currentlevel+1)+"&selectionid="+entry.getKey()+"&selectiontext="+entry.getValue());
						i++;
					}
					
					String heading="";
					if(servicetype.equals("Lands")&&Currentlevel==0)
					{
						heading="Please select the District";
					}
					else if(servicetype.equals("Lands")&&Currentlevel>0)
					{
						heading="Please select Area";
					}
					else {
					
						heading="Please select the Type of Vehicle";
					}
					ussdMenu.setAction("ShowMenu");
					ussdMenu.setHeading(heading);
					ussdMenu.setMenuItem(menuitems);
					ussdMenu.setHasBack(true);
					ussdMenu.setHasHome(true);					
				}
				else{
					if (Currentlevel==0){
						ussdMenu.setAction("Notification");
						ussdMenu.setHeading("Sorry We are having a Temparary issue");
					}
					else {				// Going to subscribe
						
						
						String heading="";
						if(servicetype.equals("Lands"))
						{
							heading="You are going to subscribe to receive SMS Alert on Lands around\n";
							//heading+=session
						}
						else 
						{
							heading="Please select Area";
						}
						ussdMenu.setAction("ShowMenu");
						ussdMenu.setHeading(heading);
						//ussdMenu.setMenuItem(menuitems);
						ussdMenu.setHasBack(true);
						ussdMenu.setHasHome(true);		
					}
					
				}
			}
			else if (MenuID.equalsIgnoreCase("sellvehiclemain"))
			{
				ussdMenu.setAction("ShowMenu");
				ussdMenu.setHeading("What's Your Plan ?");
				ussdMenu.setMenuItem(new UssdMenuItem [] {
						new UssdMenuItem("Buy my Dream Vehicle", "http://localhost:8080/smsreceiver/ussdreceiver?msisdn=%MSISDN%&menuid=vehiclemain"), 
						new UssdMenuItem("Sell out may Vehicle", "http://localhost:8080/smsreceiver/ussdreceiver?msisdn=%MSISDN%&menuid=landsmain")					
				});
			}
		
			
		 
		  
	  
 
	  ussdMenu.encode(response.getOutputStream());	  	
	
      } catch (JAXBException e) {
    	  e.printStackTrace();
      } catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
 
	}
		
		
		
		
		
		
		
		
		
		
		/*
        if (param != null) {
            
            response.setContentType("text/plain");
            response.getWriter().println(" Sessons variable already exists : "+param+"....set it to :"+SenderNumber);
            session.setAttribute("msisdn", SenderNumber);
            
        } else {
            
        	response.setContentType("text/plain");
        	session.setAttribute("msisdn", SenderNumber);
            response.getWriter().println(" Sessons variable set to  : "+SenderNumber);
            
            
        }
        */
		
	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
